/*
 * Copyright 2019 xiaomaoguai.com All right reserved. This software is the
 * confidential and proprietary information of xiaomaoguai.com ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with xiaomaoguai.com.
 */

package com.xiaomaoguai.core.next.apm.logging.logback;

import ch.qos.logback.classic.pattern.ThrowableProxyConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Context;
import com.alibaba.fastjson.JSON;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

/**
 * 异常堆栈敏感信息数据转换器
 *
 * @author chenyao
 * @since 2019年5月14日 上午11:49:42
 */
@Setter
@Getter
public class SensitiveDataThrowableProxyConverter extends ThrowableProxyConverter {
    /**
     * 日志脱敏开关
     */
    private String                 allowRun;
    /**
     * 日志脱敏关键字
     */
    private Set<SensitiveDataRule> sensitiveDataRules;

    @Override
    public String convert(ILoggingEvent event) {
        String formattedMessage = super.convert(event);
        if (getAllowRun() == null) {
            Context context = getContext();
            String allowRun = context.getProperty("SensitiveDataAllowRun");
            setAllowRun(StringUtils.defaultIfBlank(allowRun, "true"));

            String[] keys = { "SensitiveDataKeys", "SensitiveDataKeys1", "SensitiveDataKeys2", "SensitiveDataKeys3" };
            Set<SensitiveDataRule> sensitiveDataRulesInit = new LinkedHashSet<>();
            for (String key : keys) {
                String dataKeys = context.getProperty(key);
                List<SensitiveDataRule> sensitiveDataRules = JSON.parseArray(dataKeys, SensitiveDataRule.class);
                if (CollectionUtils.isNotEmpty(sensitiveDataRules)) {
                    sensitiveDataRulesInit.addAll(sensitiveDataRules);
                }
            }
            setSensitiveDataRules(sensitiveDataRulesInit);
        }

        // 获取脱敏后的日志
        return SensitiveDataConverter.filterMessage(allowRun, sensitiveDataRules, formattedMessage);
    }
}
